package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * Author 喵喵喵
 * Date 2025/6/10 11:32
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatproperties;
    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(UserLoginDTO dto) {
        //1.先做非空判断
        if (dto==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //2.组装参数,code,小程序id和小程序密钥  -->  调用微信第三方登录接口,获取openid
        String code = dto.getCode();
        String appid = weChatproperties.getAppid();
        String secret = weChatproperties.getSecret();
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        String jsonResult = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);
        JSONObject jsonObject = JSONObject.parseObject(jsonResult);
        String openid = jsonObject.getString("openid");
        if (openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //3.根据这个openid去user表中查询是否存在,如果不存在则新增(注册)
        //select * from user where  openid=openId
        User user=userMapper.getUserByOpenId(openid);
        //如果user是空,则证明当前是新用户,(第一次登录),因此需要新增
        if (user==null){
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.saveUser(user);

        }
        //4.返回user对象

        return user;
    }
}
